package com.xsp.mybatisxmlsqlparser.node;

import lombok.extern.slf4j.Slf4j;
import org.dom4j.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ReplacedElement {

    private final Map<String, List<Element>> replacedElements;

    public ReplacedElement() {
        this.replacedElements = new HashMap<>();
    }

    public Map<String, List<Element>> map() {
        return this.replacedElements;
    }

    public void add(String key, Element dom4jElement) {
        if (this.replacedElements.containsKey(key)) {
            this.replacedElements.get(key).add(dom4jElement);
        } else {
            List<Element> elements = new ArrayList<>();
            elements.add(dom4jElement);
            this.replacedElements.put(key, elements);
        }
    }

    public List<Element> get(String key) {
        return this.replacedElements.get(key);
    }

    public void clear() {
        this.replacedElements.clear();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, List<Element>> entry : this.replacedElements.entrySet()) {
            StringBuilder elementList = new StringBuilder();
            Integer index = 1;
            for (Element element : entry.getValue()) {
                elementList.append(element.getName()).append(index).append("\n");
                index++;
            }
            sb.append(entry.getKey()).append(":").append("[").append(elementList.toString()).append("]\n");
        }
        return sb.toString();
    }
}
